<template>
  <div>
    <div class="search_form">
      <el-form ref="form" :model="queryForm" label-width="100px" @submit.native.prevent>
        <el-row :gutter="20">
          <el-col :span="5">
            <el-form-item label="订单:">
              <el-select id="id-business-tags-queryForm-offerId" v-model="queryForm.offerId" clearable
                         filterable size="mini" placeholder="请选择订单名称"
                         style="width: 100%"
                         ref="customerId" @change="searchForm">
                <el-option v-for="(item,index) in offerList"
                           :key="index" :label="item.name" :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="名称:">
              <el-input size="mini" v-model="queryForm.name" placeholder="请输入模版名称"></el-input>
            </el-form-item>
          </el-col>
          <el-col span="2" style="margin-top: 4px;">
            <el-tooltip class="item" effect="dark" content="搜索" placement="top">
              <el-button id="id-business-customer-searchForm" ype="primary" icon="el-icon-search" size="small"
                         @click="searchForm" style="margin-right: 0">
                搜索
              </el-button>
            </el-tooltip>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <avue-crud
    :option="option"
    :data="data"
    :page.sync="page"
    ref="crud"
    @current-change="currentChange"
    @size-change="sizeChange"
    @refresh-change="refreshChange"
    @selection-change="selectionChange"
    @on-load="onLoad(page)"
    :loading="loadingTable"
    >
      <template slot="menuLeft" slot-scope="{size}">
        <el-button id="id-business-tags-handleAdd"
                   type="primary"
                   size="small"
                   icon="el-icon-plus"
                   plain
                   @click="addTagsTemplate">新 增
        </el-button>
        <el-button id="id-business-tags-handleDelete"
                   type="danger"
                   size="small"
                   icon="el-icon-delete"
                   plain
                   @click="deleteTemp">删 除
        </el-button>
      </template>
      <template slot-scope="{row}" slot="menu">

        <span style="padding-left: 10px;"></span>
        <el-tooltip content="编辑" placement="top">
          <el-button id="id-business-account-rowEdit" icon="el-icon-edit" type="text" @click="rowEdit(row)"
                     ></el-button>
        </el-tooltip>
        <el-tooltip content="复制" placement="top">
          <el-button id="id-business-account-rowView" size="small" icon="el-icon-document-copy" type="text"
                     @click="rowCopy(row)"></el-button>
        </el-tooltip>
        <span style="padding-left: 10px;"></span>
        <el-tooltip content="删除" placement="top">
          <el-button id="id-business-account-rowDel" icon="el-icon-delete" type="text" @click="rowDel(row)"
                     ></el-button>
        </el-tooltip>
      </template>

      <template slot="groupDiv" slot-scope="{row}">
        <el-select size="mini" v-model="row.groupDiv" @change="saveModel(row,$event)" >
          <el-option v-for="item in divList" :key="item.value" :value="item.value"
                     :label="item.label"></el-option>
        </el-select>
      </template>

      <template slot="tagDiv" slot-scope="{row}">
        <el-select size="mini" v-model="row.tagDiv"  @change="saveModel(row,$event)">
          <el-option v-for="item in divList" :key="item.value" :value="item.value"
                     :label="item.label"></el-option>
        </el-select>
      </template>
      <template slot="offerId" slot-scope="{row}">
        <el-select size="mini" v-model="row.offerIds" multiple collapse-tags @change="changeOffer(row)">
          <el-option v-for="item in getOfferListById(row.selectOfferIds)" :key="item.id" :value="item.id"
                     :label="item.name"></el-option>
        </el-select>
      </template>

      <template slot="tags" slot-scope="{row}">
        <div style="display: flex">
          <span v-for="(it,i) in getNodeName(row.tagsSnapshot)" :key="i" class="tagsStyle"
            >
            {{ it.name }}
          </span>
        </div>
      </template>
    </avue-crud>
    <el-drawer
      :wrapperClosable="false"
      size="80%" :title="drawerTitle" :visible.sync="isShowEdit" :modal-append-to-body="false" style="width:100%;"
      :close-on-click-modal="false" :before-close="handlerDrawerClose" :append-to-body="true" destroy-on-close
    >
      <el-divider></el-divider>
      <div style="margin-left: 20px;margin-top: 20px">
        <create-or-edited-creative-tags-template
          v-if="isShowEdit"
          ref="create-or-edited-tags" :offer-list="offerList"
          :tagsTree="tagsTree"
          :createTagFrom="createTagFrom"
          @on-close="handlerDrawerClose">
        </create-or-edited-creative-tags-template>
      </div>

    </el-drawer>

  </div>
</template>

<script>
import beetlesTable from "@/components/basic-components/beetles-table"
import {getOfferIdList, submitModel, getPage, removeModel} from "@/api/system/creative_tags"
import createOrEditedCreativeTagsTemplate
  from "@/views/system/components/tagsComponent/CreateOrEditedCreativeTagsTemplate"
import CreativeTagsSelect from "@/views/system/components/tagsComponent/CreativeTagsSelect"
import {deepClone} from "../../../../util/util";
import {
  getSystemTags,
  getTenantTags,
} from "@/api/system/creative_tags";
import tagsApi from "@/util/tags";

export default {
  name: "tagsTemplate",
  components: {
    CreativeTagsSelect,
    beetlesTable,
    createOrEditedCreativeTagsTemplate
  },
  props: {
    offerId: String,
    tagsTree: {
      type: Array,
      default: () => {
      }
    }
  },
  data() {

    return {
      loadingTable: false,
      loading: true,
      isShowEdit: false,
      drawerTitle: "",
      loadingOffer: false,
      queryForm: {
        offerId: '',
        name: '',
      },
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      data: null,
      divList: [
        {label: '-', value: '-'},
        {label: '_', value: '_'},
        {label: '、', value: '、'},
        {label: '/', value: '/'},
        {label: '&', value: '&'},
        {label: '~', value: '~'},
      ],
      createTagFrom: {},
      offerList: [],
      selectionList: [],
      // tagsTree:[],
      option: {
        calcHeight: 30,
        tip: false,
        searchShow: false,
        searchMenuSpan: 6,
        border: true,
        index: true,
        addBtn:false,
        viewBtn: false,
        editBtn: false,
        delBtn: false,
        menuWidth: 120,
        selection: true,
        dialogClickModal: false,
        dialogWidth: 1200,
        column: [
          {
            label: "模版名称",
            prop: "modelName",
            overHidden: true,
          },
          {
            label: "标签组、标签",
            prop: "tags",
            overHidden: true,
            width: '250px'
          },
          {
            label: "组外分隔",
            prop: "groupDiv",
          },
          {
            label: "同组分隔",
            prop: "tagDiv",
            overHidden: true,
          },
          {
            label: "关联订单",
            prop: "offerId",
          }]
      },
    }
  },
  created() {

  },
  activated() {
    // ::TODO BUG:组件切换路由不销毁,导致beetles-table组件固定表头会出现阻挡
    this.$refs.crud.handleScroll()
  },
  mounted() {
    // this.getTags();
    getOfferIdList({statusList: '0,1,2,3'}).then(res => {
      this.offerList = res.data.data
    })
  },
  computed: {
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push(ele.id);
      });
      return ids.join(",");
    }
  },
  methods: {
    buildSearch() {
      // this.query = {...this.queryForm};
    },
    searchForm() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          this.buildSearch();
          this.page.currentPage = 1
          this.onLoad(this.page)
        }
      });
    },
    getTags() {
      Promise.all([
        getSystemTags(),
        getTenantTags()
      ]).then((result) => {

        let tagsff = tagsApi.tagsAdd(result[0].data.data, result[1].data.data)
        this.tagsTree = tagsff;
      })
    },
    //获取列表
    onLoad(page, params = {}) {
      this.loading = true
      getPage(page.currentPage, page.pageSize, Object.assign({}, params, this.queryForm)).then(res => {
        let data = res.data.data
        data.records.map((item) => {
          item.tempTagDiv = item.tagDiv;
          item.tempGroupDiv = item.groupDiv;
          item.offerIds = item.offerIds ? item.offerIds.split(',') : []
          item.selectOfferIds = deepClone(item.offerIds)
        })
        this.data = data.records;
        this.page.total = data.total
        this.loading = false
      })
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page);
    },
    getOfferListById(ids) {

      // var ids = ["1519559328901574657","1519560658693009409","1519567732030291969"]
      // console.log('ids=>',ids, 'offer=>',this.offerList)
      // console.log(id)
      // let array=[];
      // this.offerList.map(item=>{
      //   if (item.id==id){
      //     array.push(item)
      //     // return;
      //   }
      // })
      // return array
      // console.log('arr', arr)

      // return this.offerList.filter(item => item.id === id)
      return this.offerList.filter(item => ids.indexOf(item.id) !== -1)
    },
    showTagsView(tagsSnapshot, name) {
      let array = [];
      tagsSnapshot.map(item => {
        if (item.type == 'system') {
          let tag = {};
          tag.name = item.name;
          tag.type = item.type;
          array.push(tag);
        } else {
          item.tags.forEach(tag => {
            tag.type = item.type;
            array.push(tag);
          })
        }
      });
      return array;
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    /**
     * 添加模版
     */
    addTagsTemplate() {
      this.drawerTitle = "新增模版"
      this.isShowEdit = true;
      this.createTagFrom = {
        modelName: "",
        offerId: "",
        groupDiv: "-",
        tagDiv: "&",
        generateStatus: 1
      };
      this.$nextTick(() => {
        this.$refs['create-or-edited-tags'].addNew();
      })

    },
    /**
     * 关闭查看/编辑弹窗
     */
    handlerDrawerClose(update) {
      this.isShowEdit = false;
      if (update === 'update') {
        this.onLoad(this.page);
      }
    },
    //删除模版标签
    deleteTemp() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.loading = true;
          return removeModel(this.ids);
        })
        .then(() => {
          this.loading = false;
          this.page.currentPage = 1,
            this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        });
    },
    rowDel(row) {
      this.loading = true;
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.loading = false;
          return removeModel(row.id);
        })
        .then(() => {
          //末端数据
          if ((this.page.total - ((this.page.currentPage - 1) * this.page.pageSize) - 1) === row.$index) {
            this.page.currentPage = this.page.currentPage - 1;
            if (this.page.currentPage === 0) {
              this.page.currentPage = 1;
            }
          }
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        });
    },
    //编辑
    rowEdit(row) {
      console.log('编辑')
      this.createTagFrom = deepClone(row);
      this.drawerTitle = "修改模版"
      this.isShowEdit = true;
      this.$nextTick(() => {
        // console.log(this.$refs['create-or-edited-tags'])
        this.$refs['create-or-edited-tags'].initData();
      })

    },
    //copy
    rowCopy(row) {
      this.createTagFrom = deepClone(row);
      this.isShowEdit = true;
      this.drawerTitle = "新增模版"
      this.createTagFrom.id = undefined;
      this.createTagFrom.offerIds = [];
      this.createTagFrom.modelName = "";
      this.$nextTick(() => {
        console.log(this.$refs['create-or-edited-tags'])
        this.$refs['create-or-edited-tags'].initData();
      })
    },
    saveModel(row,event){
      if (row.groupDiv === row.tagDiv) {
        this.$message({
          message: '组内分隔和同组分隔不可以使用相同分隔符!',
          type: 'error'
        })
        row.groupDiv=row.tempGroupDiv;
        row.tagDiv=row.tempTagDiv;
        return
      }
      this.loading = true;
      row.generateName = this.buildName(row);
      if (Array.isArray(row.offerIds)){
        row.offerIds = row.offerIds.join(',')
      }
      console.log('row', row)
      submitModel(row).then(res => {
        this.loading = false;
        this.$message.success('更新模版成功')
        row.tempGroupDiv=row.groupDiv;
        row.tempTagDiv=row.tagDiv;
        if (typeof(row.offerIds)=='string'){
          row.offerIds = row.offerIds.split(',')
        }
      }).catch(ex=>{
        this.loading=false;
      });
    },
    buildName(row){
      let name='';
      let val=[];
      if ((typeof (row.nameRules)==='string')){
        val=JSON.parse(row.nameRules)
      }
      if (val.length>0){
        val.map(item=>{
          if (item.type=='system'){
            if (name===''){
              name+='{'+item.code+'}';
            }else {
              name+=row.groupDiv+'{'+item.code+'}';
            }

          }else {
            let tags=item.tags;
            tags.forEach((it,index)=>{
              if (index==0){
                name+= row.groupDiv+it.name
              }else {
                name+= row.tagDiv+it.name
              }
            })
          }
        });
      }
      return name;
    },
    getNodeName(node){

      if (typeof(node)==='string'){
        return JSON.parse(node)
      }
      return node;
    },
    // 修改关联订单
    changeOffer(row) {
      this.loading = true
      row.offerIds = row.offerIds.join(',')
      submitModel(row).then(res => {
        this.loading = false;
        this.$message.success('更新模版成功')
        row.offerIds = row.offerIds.split(',')
      }).catch(ex => {
        this.loading = false;
        row.offerIds = row.offerIds.split(',')
      });
    }

  },

}
</script>
<style scoped lang="scss">
.tagsStyle {
  height: 25px;
  margin-bottom: 3px;
  padding: 0 10px;
  border-radius: 4px;
  background: white;
  font-size: 10px;
  margin-right: 5px;
  line-height: 25px;
  border: 1px solid rgba(232, 232, 232, 100);
  text-align: center;
}
</style>

